<template>
  <el-dialog :close-on-click-modal="false" :title="$tt('label_income_good_measure')" :visible.sync="visible"
    custom-class="dialog_big" destroy-on-close>
    <div v-loading="loading">
      <el-form :model="form" ref="form" label-position="top">
        <el-form-item :label="$tt('label_file_upload')">

          <button_select_file @input="selectFile" type="primary">
            {{ $tt('label_import_excel') }}
            <i class="el-icon-upload2 el-icon--right"></i>
          </button_select_file>
          <el-button @click="downloadXlsx" size="mini" type="primary">{{ $tt('label_download_import_template') }}<i
              class="el-icon-download el-icon--right"></i></el-button>
        </el-form-item>
        <el-form-item prop="tableList" :label="$tt('label_box_list')">
          <ex_super_table ref="table" v-bind="tableBaseOption" :data="form.tableList" height="600">
          </ex_super_table>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog_footer">
        <el-button @click="visible = false">{{ $tt('label_cancel') }}</el-button>
        <el-button type="primary" @click="submit">{{ $tt('label_submit') }}</el-button>
      </span>
    </div>

  </el-dialog>
</template>

<script>
import volume_input from '@/component/wms/volume_input.vue';
import select_file_temp from '@/component/base/select_file_temp'
// import xlsx from '@/asset/xlsx.full.min.js'
import ExcelJS from '@/asset/exceljs.bare.min.js'

export default {
  name: 'transfer_receive_measure',
  components: { volume_input, select_file_temp, },
  data() {
    return {

      visible: false,
      loading: false,
      form: {
        tableList: [],
      },
      tableBaseOption: {
        attrs: { 'cell-class-name': this.cellClassName, 'span-method': this.objectSpanMethod },
        model: [
          { key: 'receivingCode', label: 'label_inbound_code', 'min-width': 160, },
          { key: 'customerCode', label: 'label_customer_info', 'width': 120, 'show-overflow-tooltip': true, },
          {
            key: 'orderInfo', label: 'label_inbound_info', 'width': 120,
            render: (h, { row }) => (<div>
              <div>{this.$tt('label_expected_box_number')}:{row.expectBoxQty}</div>
              <div>{this.$tt('label_receiving_box_number')}:{row.receivingBoxQty}</div>
              <div>{this.$tt('label_expected_sku_number')}:{row.expectSkuQty}</div>
              <div>{this.$tt('label_receiving_number')}:{row.receivingSkuQty}</div>
            </div>)
          },


          { key: 'boxNo', label: 'label_box_code', 'width': 140, },
          {
            key: 'boxWeight', label: 'label_expect_box_weight', 'width': 110,
            formatter: (r, c, v) => this.$addUnit(v, 'kg'),
          },
          {
            key: 'boxVolume', label: 'label_expect_box_volume', 'width': 110,
            formatter: (r, c, v) => this.$addUnit(v, 'm³'),
          },
          {
            key: 'measureWeight', label: 'label_measure_box_weight', 'width': 160,
            'label-class-name': 'label_require_before',
            render: (h, { column, row, index }) => {
              return (
                <el-form-item
                  prop={`tableList.${index}.${column.property}`}
                  rules={this.formRules[column.property]}

                >
                  <ex_super_input
                    value={row.measureWeight}
                    onInput={value => {
                      this.$set(row, 'measureWeight', value)
                    }}
                    placeholder={this.$tt('label_measure_weight')}
                    append="kg"
                  >
                  </ex_super_input>
                </el-form-item>
              );
            }
          },
          {
            key: 'measureVolume', label: 'label_measure_box_volume', 'min-width': 240,
            renderHeader: (h, { column, $index }) => (<div>
              <div class="table-require">{column.label}</div>
              <el-button-group>
                <el-button size="mini" onClick={e => this.$refs.table.$refs.volume_input.forEach(vi => vi.changeType('LWH'))}> {this.$tt('label_lwh')}</el-button>
                <el-button size="mini" onClick={e => this.$refs.table.$refs.volume_input.forEach(vi => vi.changeType('V'))}>{this.$tt('label_volume')}</el-button>
              </el-button-group>
            </div>),
            render: (h, { column, row, index }) => {
              return (
                <el-form-item
                  prop={`tableList.${index}.${column.property}`}
                  rules={this.formRules[column.property]}
                >
                  {
                    h(volume_input, {
                      ref: 'volume_input',
                      key: row.boxId,
                      refInFor: true,
                      props: {
                        value: row.measureVolume,
                        placeholderLWH: this.$tt('label_l_w_h'),
                        placeholderV: this.$tt('label_measure_volume'),
                      },
                      on: {
                        input: (e) => this.$set(row, 'measureVolume', e)
                      }
                    })
                  }

                </el-form-item>
              );
            }
          },
        ],
      },
      formRules: {
        measureWeight: {
          required: true, trigger: 'change',
          validator: (r, v, cb) => {
            if (!this.$reg.DigitNumber(v, 3, 9)) {
              return cb(this.$tt("tip_only_digit_int_length", { digit: 3, int: 9 }))
            }
            cb()
          }
        },
        measureVolume: {
          required: true, trigger: 'change',
          validator: (r, v, cb) => {
            if (Number.isNaN(v)) {
              return cb(this.$tt("tip_lwh_use_split"))
            } else if (!this.$reg.DigitNumber(v, 6, 9)) {
              return cb(this.$tt("tip_only_digit_int_length", { digit: 6, int: 9 }))
            }
            cb()
          }
        },
      },
      xlsxStructure: {
        receivingCode: { key: 'receivingCode', label: this.$tt('label_inbound_code'), index: 1, },
        boxNo: { key: 'boxNo', label: this.$tt('label_box_code'), index: 2, },
        measureWeight: { key: 'measureWeight', label: this.$tt('label_measure_box_weight'), index: 3, },
        measureVolume: { key: 'measureVolume', label: this.$tt('label_measure_box_volume'), index: 4, },
      }
    }
  },
  props: {
  },
  methods: {
    selectFile(e) {

      let reader = new FileReader();
      const xlsxStructure = this.xlsxStructure
      reader.onload = (e) => {
        const data = e.target.result
        new ExcelJS.Workbook().xlsx.load(data).then(workbook => {
          const worksheet = workbook.getWorksheet(1)
          this.$refs.table.$refs.volume_input.forEach(vi => vi.changeType('V'))
          worksheet.eachRow((row, rowNumber) => {
            if (rowNumber == 1) return
            const item = _.find(this.form.tableList,
              indata => indata.receivingCode == row.getCell(xlsxStructure['receivingCode'].index).text &&
                indata.boxNo == row.getCell(xlsxStructure['boxNo'].index).text)
            if (item) {
              item.measureWeight = row.getCell(xlsxStructure['measureWeight'].index).text //.values[xlsxStructure['measureWeight'].index]
              item.measureVolume = row.getCell(xlsxStructure['measureVolume'].index).text //.values[xlsxStructure['measureVolume'].index]
            }
          });
        })
      };
      reader.readAsArrayBuffer(e[0]);
    },

    downloadXlsx() {
      if (_.isEmpty(this.form.tableList)) {
        this.$alert(this.$tt('tip_no_has_can_operate_data'), this.$tt("label_tip"), {
          type: 'warning'
        }).then(() => {

        }).catch(() => {
        });
        return
      }
      // 1. 创建一个工作簿 workbook
      // const workBook = xlsx.utils.book_new()
      // const label_inbound_code = this.$tt('label_inbound_code')
      // const label_box_code = this.$tt('label_box_code')

      // const label_measure_box_weight = this.$tt('label_measure_box_weight')
      // const label_measure_box_volume = this.$tt('label_measure_box_volume')

      // const list = this.form.tableList.map(it => {
      //   const obj = {}
      //   obj[label_inbound_code] = it.receivingCode
      //   obj[label_box_code] = it.boxNo
      //   obj[label_measure_box_weight] = it.measureWeight
      //   obj[label_measure_box_volume] = it.measureVolume
      //   return obj
      // })

      // // 2. 创建工作表 worksheet
      // const workSheet = xlsx.utils.json_to_sheet(list)
      // // 3. 将工作表放入工作簿中
      // xlsx.utils.book_append_sheet(workBook, workSheet)
      // // 4. 生成数据保存
      // xlsx.writeFile(workBook, `${this.$tt('label_transit_measure_import_template')}${new Date().getTime()}.xlsx`, {
      //   bookType: 'xlsx'
      // })




      const wb = new ExcelJS.Workbook()
      const worksheet = wb.addWorksheet(this.$tt('label_transit_measure_import_template'))

      const sts = _.sortBy(Object.values(this.xlsxStructure), 'index')
      worksheet.addRow(sts.map(it => it.label));
      this.form.tableList.forEach(it => {
        worksheet.addRow(sts.map(s => it[s.key] ? it[s.key] : null));
      })


      wb.xlsx.writeBuffer().then(buffer => {
        this.$downloadBuffer({
          buffer,
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          filename: `${this.$tt('label_transit_measure_import_template')}${new Date().getTime()}.xlsx`,
        })
      })
    },
    // beforeUpload(file) {
    //   this.loadingImport = this.$loading({
    //     lock: true,
    //     text: 'Loading',
    //     spinner: 'el-icon-loading',
    //   });
    // },
    // uploadExcelSuccess(response, file, fileList) {
    //   if (response.code == 0) {
    //     const list = response.data.rows
    //     list.forEach(it => {
    //       it.boxWeight = it.weight
    //       it.boxVolume = it.volume

    //     })
    //     this.$set(this.importForm, 'rows', list)
    //     this.$message.success(this.$tt('label_import_success'));
    //   } else {
    //     this.$message.error(response.message || this.$tt('label_import_fail'));
    //   }
    //   if (this.$refs.upload) this.$refs.upload.clearFiles()
    //   if (this.loadingImport) this.loadingImport.close();
    // },
    // uploadExcelError(response, file, fileList) {
    //   this.$message.error(this.$tt('label_import_fail'))
    //   if (this.loadingImport) this.loadingImport.close();
    // },
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (['orderInfo',].includes(column.property)) {
        return "revert_cell_border"
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (['receivingCode', 'customerCode', 'orderInfo', 'orderSku',].includes(column.property)) {
        return { rowspan: row.rowspanOrder, colspan: 1 }
      }

    },
    show({ tableList }) {
      this.loading = true
      this.$ajax({
        url: "/wms-api/inbound/WmsInboundTransitReceivingRpc/selectBatchDetail.json",
        method: 'post',
        data: { ids: tableList.map(it => it.id) },
        success: (res) => {
          this.form.tableList = _.flatMap(res.data.rows, it => {
            const boxUnion = _.unionBy(it.detailList.filter(sku => sku.boxReceivingStatus != 'NOT_RECEIVING'), 'boxNo')
            boxUnion.forEach((box, boxIndex) => {
              box.expectBoxQty = it.expectBoxQty
              box.expectSkuQty = it.expectSkuQty

              box.receivingBoxQty = it.receivingBoxQty
              box.receivingSkuQty = it.receivingSkuQty
              box.measureWeight = box.boxMeasureOrderWeight
              box.measureVolume = box.boxMeasureOrderVolume

              if (boxIndex == 0) {
                box.rowspanOrder = boxUnion.length
              } else {
                box.rowspanOrder = 0
              }
            })

            return boxUnion
          })
        },
        complete: () => {
          this.loading = false
        }
      })
      this.visible = true

    },


    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let boxGroup = _.groupBy(this.form.tableList, 'receivingCode')
          let measureOrderList = []
          _.forOwn(boxGroup, (v, k) => {
            measureOrderList.push({
              inboundOrderCode: k, measureMode: "BOX",
              measureBoxList: v.map(it => ({
                boxNo: it.boxNo,
                measureWeight: it.measureWeight,
                measureVolume: it.measureVolume,
              }))
            })
          })
          this.$ajax({
            url: "/wms-api/inbound/WmsInboundTransitReceivingRpc/measureBatch.json",
            method: 'post',
            type: 'json',
            loading: this.$tt('tip_submiting'),
            data: { measureOrderList },
            success: (res) => {
              this.$message.success(this.$tt("tip_submit_success"))
              this.$emit("submitSuccess")
              this.visible = false
            },
          })
        } else {
          this.$message.error(this.$t('form_validate_error'))
          return false;
        }
      });
      return
      // if (this.tableList.some(it => !it.temporaryAreaId)) {
      //   return this.$message.error(this.$tt("tip_please_select_warehouse_area"))
      // }




    }

  }
}
</script>
